package com.zhenyi.search;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import com.utils.PathUtils;

public class Search2 {
	// private String indexStorePath = "D:\\test\\index";
	private String indexStorePath = PathUtils.getPath("search", "resource", "index");

	// 创建索引
	void createIndex(String inputDir) {
		try {
			Directory indexDirectory = FSDirectory.open(new File(indexStorePath).toPath());

			// 中文分词器
			// SmartChineseAnalyzer analyzer=new SmartChineseAnalyzer()

			// Analyzer analyzer = new
			// JcsegAnalyzer(JcsegTaskConfig.COMPLEX_MODE)

			// 英文、中文 分词器
			Analyzer analyzer = new StandardAnalyzer();

			IndexWriterConfig config = new IndexWriterConfig(analyzer);

			// 利用分词工具创建 IndexWriter
			IndexWriter writer = new IndexWriter(indexDirectory, config);
			File filesDir = new File(inputDir);
			// 取得 要建立 索引的文件数组
			File[] files = filesDir.listFiles();
			for (int i = 0; i < files.length; i++) {
				String fileName = files[i].getName();
				if (fileName.substring(fileName.lastIndexOf(".")) == ".txt") {
					// 创建新的Document
					Document doc = new Document();
					// 为文件名创建一个 Field
					StoredField storedField = new StoredField("filename", files[i].getName());
					// Field field = new
					// Field("filename",files[i].getName(),Field.Store.YES)
					doc.add(storedField);

					// TextField textField= new TextField("body",new
					// FileReader(files[i]))
					String body = loadFileToString(files[i]);

					TextField textField = new TextField("body", body, Field.Store.YES);
					// field = new
					// Field("content",loadFileToString(files[i]),Field.Store.NO,Field.Index.TOKENIZED)
					doc.add(textField);
					// 把Document加入 IndexWriter
					writer.addDocument(doc);
				}
			}
			writer.commit();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	// 加载文档 生成字符串
	String loadFileToString(File f) {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"));
			StringBuffer sb = new StringBuffer();
			String line = br.readLine();
			while (line != null) {
				sb.append(line);
				line = br.readLine();
			}
			br.close();
			return sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void main(String[] args) {
		Search2 pr = new Search2();
		String path = PathUtils.getPath("search", "resource");
		System.out.println();
		pr.createIndex(path);
	}
}
